#include "in2post.h"

void show_stack(LNODE *ptr){
    while(ptr != NULL){
        printf("%c", ptr->data);
        ptr = ptr->link;
    }
    printf("\n");
}
int empty(LNODE *ptr){
    if(ptr == NULL){
        return 1;
    }else{
        return 0;
    }
}
void push(LNODE **ptr, char item){
    LNODE *p;
    if(empty(*ptr)){
        p = malloc(sizeof(LNODE));
        if(p != NULL){
            p->data = item;
            p->link = NULL;
            *ptr = p;
        }
    } else {
        p = malloc(sizeof(LNODE));
        if(p != NULL){
            p->data = item;
            p->link = *ptr;
            *ptr = p;
        }
    }
}

void pop(LNODE **ptr, char *item){
    LNODE *p1;
    p1 = *ptr;
    if(empty(p1)){
        *item = '\0';
    } else{
        *item = p1->data;
        *ptr = p1->link;
        free(p1);
    }
}
//-------------------
int isoperator(char e){
	if(e == '+' || e == '-' || e == '*' || e == '/' || e == '%')
		return 1;
	else
		return 0;
}

int priority(char e){
	int pri = 0;
	if(e == '*' || e == '/' || e =='%')
		pri = 2;
	else{
		if(e == '+' || e == '-')
			pri = 1;
	}
	return pri;
}

void infix2postfix(char* infix, char * postfix, int insertspace)
{
	char *i,*p;
	LNODE *X = NULL;
	char n1;
	empty(X);
	i = infix;
	p = postfix;
	
	while(*i){
		while(*i == ' ' || *i == '\t'){
			i++;
		}
		if( isdigit(*i) || isalpha(*i)){
			while( isdigit(*i) || isalpha(*i)){
				*p = *i;
				p++;
				i++;
			}
			/*SPACE CODE*/
			if(insertspace){
				*p = ' ';
				p++;
			}
		}	/*END SPACE CODE*/
		if( *i == '(' ){
			push(&X,*i);
			i++;
		}
		if( *i == ')'){
			pop(&X, &n1);
			while( n1 != '(' ){
				*p = n1;
				p++;
				/*SPACE CODE*/
				if(insertspace){
					*p = ' ';
					p++;
				}
				/*END SPACE CODE*/
				pop(&X, &n1);
			}
			i++;
		}
		
		if( isoperator(*i) ){
			if(empty(X)){
				push(&X,*i);
			}
			else{
				pop(&X, &n1);
				while(priority(n1) >= priority(*i)){
					*p = n1;
					p++;
					/*SPACE CODE*/
					if(insertspace){
						*p = ' ';
						p++;
					}/*END SPACE CODE*/
					pop(&X, &n1);
				}
				push(&X,n1);
				push(&X,*i);
			}
			i++;
		}
	}
	while(!empty(X)){
		pop(&X, &n1);
		*p = n1;
		p++;
		/*SPACE CODE*/
		if(insertspace){
			*p = ' ';
			p++;
		}/*END SPACE CODE*/
	}
	*p = '\0';
}
